﻿using Ruici.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ruici.Web.Services.CRS_Service;
using RuiciWebSite.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Globalization;
using Ruici.Web.Services.ServiceForWeb;
using System.IO;
using RuiciWebSite.Common;
using Ruici.Web.Services.Model;

namespace RuiciWebSite.Controllers
{
    public class PersonalCenterController : Controller
    {
        private UserReservitionBll userBll = new UserReservitionBll();
        private UserBll userInfoBll = new UserBll();
        private DocInfoBll docBll = new DocInfoBll();
        private RuiciCommoms common = new RuiciCommoms();
        // GET: PersonalCenter
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult GetUserReservision()
        {
            int iPid = int.Parse(Session["pid"].ToString());
            string sDocidString = "";
            List<resvIntention> userResvList = userBll.getResvIntentionList(iPid);
            List<ReservisionInfo> resvInfoList = new List<ReservisionInfo>();

            foreach (resvIntention resv in userResvList)
            {
                if (resv.Status != 8)
                {
                    ReservisionInfo resvInfo = new ReservisionInfo();
                    ReservDate resvDate = new ReservDate();
                    Doctor resvDoc = new Doctor();
                    VisitType visitType = new VisitType();
                    Address addr = new Address();
                    ActionButton act = new ActionButton();

                    resvDate.Date = resv.ResvDate.ToString("yyyy-MM-dd");
                    resvDate.Time = resv.Duration;
                    resvDoc.DoctorId = resv.DoctorId;
                    resvDoc.DoctorName = resv.DoctorName;
                    if (string.IsNullOrEmpty(sDocidString))
                        sDocidString = sDocidString + "'" + resv.DoctorId.ToString() + "'";
                    else
                        sDocidString = sDocidString + ",'" + resv.DoctorId.ToString() + "'";

                    if (resv.IsRemote)
                    {
                        visitType.TypeName = "远程";
                        visitType.TypeCls = true;
                    }
                    else
                    {
                        visitType.TypeName = "线下";
                        visitType.TypeCls = false;
                    }

                    resvDoc.visitType = visitType;
                    addr.HospitalId = resv.HospId;
                    addr.HospitalName = resv.HospName;
                    addr.HospitalAddress = resv.VisitAddress;
                    resvInfo.visitID = resv.TrId;
                    resvInfo.reservDate = resvDate;
                    resvInfo.expert = resvDoc;
                    resvInfo.addr = addr;
                    resvInfo.patient = resv.Name;
                    resvInfo.Fee = resv.Price.ToString();
                    resvInfo.btn = act;
                    resvInfo.Status = int.Parse(resv.Status.ToString());

                    resvInfoList.Add(resvInfo);
                }
            }

            List<DoctorInfoResponse> doctorInfo = docBll.GetDoctorListById(sDocidString);
            foreach (ReservisionInfo reservistion in resvInfoList)
            {
                foreach (DoctorInfoResponse doctor in doctorInfo)
                {
                    if (reservistion.expert.DoctorId.ToString() == doctor.id)
                    {
                        reservistion.expert.DoctorTitle = doctor.titleName;
                        reservistion.expert.DoctorDepartment = doctor.depName2;
                        break;
                    }
                }
            }
            resvInfoList = resvInfoList.OrderByDescending(o => o.reservDate.Date).ToList<ReservisionInfo>();

            return Json(resvInfoList, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取案例列表
        /// </summary>
        /// <param name="reservInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetCasesList(ReservisionInfo reservInfo)
        {
            int iPid = int.Parse(Session["pid"].ToString());
            string sDocidString = "";
            List<string> DocIdList = new List<string>();

            PatientInfoModel patientInforModel;
            List<PatientInfoModel> patientList = new List<PatientInfoModel>();

            if (reservInfo.expert != null)
            {
                string patientInfo = userBll.GetUserCaseListByTrId(iPid, reservInfo.addr.HospitalId, reservInfo.visitID);
                JArray patientInfoArray = (JArray)JsonConvert.DeserializeObject(patientInfo);
                JEnumerable<JToken> patinetInforList = patientInfoArray.Children();

                foreach (JToken patient in patinetInforList)
                {
                    patientInforModel = new PatientInfoModel();

                    patientInforModel.caseId = patient["病历ID"].ToString();
                    patientInforModel.pid = int.Parse(patient["PID"].ToString());
                    patientInforModel.visitId = int.Parse(patient["就诊ID"].ToString());
                    patientInforModel.caseName = patient["病历名称"].ToString();
                    patientInforModel.visitName = patient["就诊人"].ToString();
                    patientInforModel.visitYear = patient["就诊日期"].ToString().Substring(0, 4);
                    patientInforModel.visitMonthDay = patient["就诊日期"].ToString().Substring(4, 2) + "/" + patient["就诊日期"].ToString().Substring(5, 2);
                    patientInforModel.OrgId = patient["诊所ID"].ToString();
                    patientInforModel.doctorId = patient["接诊医生工号"].ToString();
                    patientInforModel.doctorName = patient["接诊医生姓名"].ToString();
                    patientInforModel.visitType = patient["类型"].ToString();
                    patientInforModel.diagnosicResult = patient["诊断结论"].ToString();
                    patientInforModel.symptom = patient["主诉"].ToString();
                    patientInforModel.medicalHistory = patient["既往病史"].ToString();
                    patientInforModel.advise = patient["诊断建议"].ToString();
                    patientInforModel.price = patient["费用"].ToString();

                    patientList.Add(patientInforModel);
                }
            }
            else
            {
                string patientInfo = userBll.getPatientInforManifest(iPid);
                JArray patientInfoArray = (JArray)JsonConvert.DeserializeObject(patientInfo);
                JEnumerable<JToken> patinetInforList = patientInfoArray.Children();

                foreach (JToken patient in patinetInforList)
                {
                    patientInforModel = new PatientInfoModel();
                    patientInforModel.caseId = patient["病历ID"].ToString();
                    patientInforModel.pid = int.Parse(patient["PID"].ToString());
                    patientInforModel.visitId = int.Parse(patient["就诊ID"].ToString());
                    patientInforModel.caseName = patient["病历名称"].ToString();
                    patientInforModel.visitName = patient["就诊人"].ToString();
                    patientInforModel.visitYear = patient["就诊日期"].ToString().Substring(0, 4);
                    patientInforModel.visitMonthDay = patient["就诊日期"].ToString().Substring(4, 2) + "/" + patient["就诊日期"].ToString().Substring(6, 2);
                    patientInforModel.visitDate = DateTime.Parse(patient["就诊日期"].ToString().Substring(0, 4) + "-" + Convert.ToInt32(patient["就诊日期"].ToString().Substring(4, 2)) + "-" + patient["就诊日期"].ToString().Substring(6, 2));
                    patientInforModel.OrgId = patient["诊所ID"].ToString();
                    patientInforModel.doctorId = patient["接诊医生工号"].ToString();
                    patientInforModel.doctorName = patient["接诊医生姓名"].ToString();
                    patientInforModel.visitType = patient["类型"].ToString();
                    patientInforModel.diagnosicResult = patient["诊断结论"].ToString();
                    patientInforModel.symptom = patient["主诉"].ToString();
                    patientInforModel.medicalHistory = patient["既往病史"].ToString();
                    patientInforModel.advise = patient["诊断建议"].ToString();
                    patientInforModel.price = patient["费用"].ToString();

                    if (string.IsNullOrEmpty(sDocidString))
                        sDocidString = sDocidString + "'" + patientInforModel.doctorId + "'";
                    else
                        sDocidString = sDocidString + ",'" + patientInforModel.doctorId + "'";

                    patientList.Add(patientInforModel);
                }

                JEnumerable<JToken> DoctorInfo = userBll.GetDoctorListByNumber(sDocidString);
                foreach (PatientInfoModel patient in patientList)
                {
                    foreach (JToken doctor in DoctorInfo)
                    {
                        if (patient.doctorId == doctor["doctorNumber"].ToString())
                        {
                            patient.photoPicUrl = RuiciCommoms._sImgPath + doctor["image"].ToString();
                            patient.department = doctor["deptName"].ToString();
                            patient.title = doctor["titleName"].ToString();
                            break;
                        }
                    }
                }
            }

            patientList = patientList.OrderByDescending(o => o.visitDate).ToList<PatientInfoModel>();

            return Json(patientList, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetEReportDetail(PatientInfoModel patienInfo)
        {
            string EReportDetail = userBll.getEReportDetail(int.Parse(patienInfo.caseId), int.Parse(patienInfo.OrgId));
            if (!string.IsNullOrEmpty(EReportDetail))
                return Json(EReportDetail, JsonRequestBehavior.AllowGet);
            return Json(new ReturnCode(-1, "获取失败"), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 案例报告
        /// </summary>
        /// <param name="patienInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetCaseReportList(PatientInfoModel patienInfo)
        {
            string sEReportList = userBll.getEReportList(patienInfo.visitId);
            if (!string.IsNullOrEmpty(sEReportList))
            {
                JArray caseInfoArray = (JArray)JsonConvert.DeserializeObject(sEReportList);
                JEnumerable<JToken> caseInfoList = caseInfoArray.Children();
                CaseReportInfo caseReportModel;
                List<CaseReportInfo> caseReportList = new List<CaseReportInfo>();

                foreach (JToken caseReport in caseInfoList)
                {
                    caseReportModel = new CaseReportInfo();

                    caseReportModel.reportId = int.Parse(caseReport["ID"].ToString());
                    caseReportModel.reportName = caseReport["报告名称"].ToString();
                    caseReportModel.orgid = int.Parse(caseReport["ORGID"].ToString());
                    caseReportModel.hospital = caseReport["医院"].ToString();
                    caseReportModel.ReportType = caseReport["报告单类别"].ToString();
                    caseReportModel.instance = caseReport["样本"].ToString();
                    caseReportModel.checkDepartment = caseReport["检验单位"].ToString();
                    caseReportModel.caseId = int.Parse(caseReport["TrID"].ToString());
                    caseReportModel.reportDate = caseReport["报告日期"].ToString();
                    caseReportModel.pid = int.Parse(caseReport["PID"].ToString());

                    string sReportDetail = userBll.getReportDetail(caseReportModel.reportId, caseReportModel.orgid, caseReportModel.ReportType);

                    JArray reportDetailArray = (JArray)JsonConvert.DeserializeObject(sReportDetail);
                    JEnumerable<JToken> reportDetailList = reportDetailArray.Children();

                    foreach (JToken reportDetail in reportDetailList)
                    {
                        caseReportModel.checkDepartment = reportDetail["科室"].ToString();
                        break;
                    }

                    caseReportList.Add(caseReportModel);
                }
                return Json(caseReportList, JsonRequestBehavior.AllowGet);
            }
            return Json(new ReturnCode(-1, "获取失败"), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 详情展示
        /// </summary>
        /// <param name="caseInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ViewDetail(CaseReportInfo caseInfo)
        {
            string sReportDetailHTML = userBll.getCaseReportDetail(caseInfo.reportId, caseInfo.orgid, caseInfo.ReportType);
            if (!string.IsNullOrEmpty(sReportDetailHTML))
            {
                return Json(sReportDetailHTML, JsonRequestBehavior.AllowGet);
            }
            return Json(new ReturnCode(-1, "获取失败"), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 来访病人列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetPatientVisitList()
        {
            int iPid = int.Parse(Session["pid"].ToString());
            List<FamilyMember> patientInfoList = userBll.getPatientVisitorList(iPid);
            List<FamilyMemberModel> patientVisitList = new List<FamilyMemberModel>();
            FamilyMemberModel patientVisit;

            if (patientInfoList != null)
            {
                foreach (FamilyMember member in patientInfoList)
                {
                    patientVisit = new FamilyMemberModel();
                    patientVisit.Age = DateTime.Now.Year - Convert.ToDateTime(member.Birthday).Year;
                    patientVisit.Id = member.Id;
                    patientVisit.Pid = member.Pid;
                    patientVisit.Relationship = member.Relationship;
                    patientVisit.IDCardNo = member.IDCardNo;
                    patientVisit.IsDefault = member.IsDefault;
                    patientVisit.Remark = member.Remark;
                    patientVisit.UpdateTime = member.UpdateTime;
                    patientVisit.Gender = member.Gender;
                    patientVisit.FamilyPID = member.FamilyPID;
                    patientVisit.FamilyName = member.FamilyName;
                    patientVisit.FamilyMobile = member.FamilyMobile;
                    patientVisit.FamilyAddress = member.FamilyAddress;
                    patientVisit.CreateTime = member.CreateTime;
                    patientVisit.Birthday = member.Birthday;

                    patientVisitList.Add(patientVisit);
                }
            }

            return Json(patientVisitList, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 添加来访病人
        /// </summary>
        /// <param name="patientVisitor"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddPatientVisitor(PatientVisitorModel patientVisitor)
        {
            int iPid = int.Parse(Session["pid"].ToString());
            bool bResult = false;

            string sErrorMessage = common.CheckValidateCode(Session, patientVisitor.editPhone, patientVisitor.editCode);

            if (!string.IsNullOrEmpty(sErrorMessage))
                return Json(new ReturnCode(-1, sErrorMessage), JsonRequestBehavior.AllowGet);


            if (patientVisitor != null)
                bResult = userBll.AddPatientVisitor(iPid, patientVisitor.editName, patientVisitor.editPhone, patientVisitor.editCard, patientVisitor.editDefault);

            if (bResult)
                return GetPatientVisitList();

            return Json(new ReturnCode(-1, "添加失败"), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="patientVisitor"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetValidateCode(PatientVisitorModel patientVisitor)
        {
            if (!string.IsNullOrEmpty(patientVisitor.editPhone))
            {
                common.GenerateValidateCode(Session, patientVisitor.editPhone);
                userInfoBll.SendMessage(patientVisitor.editPhone, Session["ValidationCode"].ToString());
                return Json(new ReturnCode(1, "验证码已发送，请注意查收!"), JsonRequestBehavior.AllowGet);
            }
            return Json(new ReturnCode(-1, "获取验证码失败，请重试"), JsonRequestBehavior.AllowGet);

        }
        /// <summary>
        /// 更新来访病人信息
        /// </summary>
        /// <param name="patientVisitor"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdatePatientVisitor(PatientVisitorModel patientVisitor)
        {
            bool bUpdateResult = false;
            int iPid = int.Parse(Session["pid"].ToString());

            if (!(patientVisitor.editCode == "000000"))
            {
                string sErrorMessage = common.CheckValidateCode(Session, patientVisitor.editPhone, patientVisitor.editCode);

                if (!string.IsNullOrEmpty(sErrorMessage))
                    return Json(new ReturnCode(-1, sErrorMessage), JsonRequestBehavior.AllowGet);
            }

            if (patientVisitor != null)
                bUpdateResult = userBll.UpdatePatientVisitor(iPid, patientVisitor.visitID, patientVisitor.editName, patientVisitor.editPhone, patientVisitor.editCard, patientVisitor.editDefault);

            if (bUpdateResult)
            {
                if (patientVisitor.editName == Session["userName"].ToString())
                {
                    userInfoBll.updateUser(Session["userName"].ToString(), patientVisitor.editCard, int.Parse(Session["pid"].ToString()));
                }

                return GetPatientVisitList();
            }


            return Json(new ReturnCode(-1, "更新失败"), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 删除来访病人
        /// </summary>
        /// <param name="patientInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelPatientVisitor(FamilyMemberModel patientInfo)
        {
            bool bResult = false;
            int iPid = int.Parse(Session["pid"].ToString());
            if (patientInfo != null)
                bResult = userBll.DeletePatientVisitor(patientInfo.Id, iPid);

            if (bResult)
                return GetPatientVisitList();

            return Json(new ReturnCode(-1, "删除失败"), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取用户详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetUserInfo()
        {
            int iPid = int.Parse(Session["pid"].ToString());
            string sPhoneNo = Session["mobile"].ToString();
            Member user = userBll.GetUserInfo(iPid);
            RegisterViewModel UserInfo = new RegisterViewModel();
            WebAccount account = userInfoBll.getWebAccountByMobile(sPhoneNo);
            List<FamilyMember> patientInfoList = userBll.getPatientVisitorList(iPid);
            FamilyMember userVisit = null;
            if (patientInfoList.Count != 0 && !string.IsNullOrEmpty(user.Name))
            {
                List<FamilyMember> patientList = patientInfoList.Where(a => a.FamilyName == user.Name && a.Pid == user.PID).ToList();
                if (patientList.Count != 0)
                {
                    userVisit = patientList.First();
                }
            }

            if (user != null && account != null)
            {
                if (userVisit != null)
                {
                    UserInfo.visitId = userVisit.Id;
                    UserInfo.IsDefault = userVisit.IsDefault;
                }

                UserInfo.Mobile = user.Mobile;
                UserInfo.Name = user.Name;
                UserInfo.Gender = user.Sex;
                if (user.MemberCertList != null)
                    UserInfo.CertCode = user.MemberCertList[0].CertNo;
                UserInfo.picUrl = RuiciCommoms._sUploadImgPath + iPid + "Photo.jpg";

                return Json(UserInfo, JsonRequestBehavior.AllowGet);
            }

            return Json(new ReturnCode(-1, "获取失败"), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="UserInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveUserInfo(RegisterViewModel UserInfo)
        {
            int iPid = int.Parse(Session["pid"].ToString());
            bool bUpdateResult = false;

            if (UserInfo == null)
                return Json(new ReturnCode(-1, "请检查是否填写了您的个人信息。"), JsonRequestBehavior.AllowGet);

            bUpdateResult = userInfoBll.updateUser(UserInfo.Name, UserInfo.CertCode, int.Parse(Session["pid"].ToString()), UserInfo.Gender);

            if (bUpdateResult)
            {
                WebAccount webAccount = userInfoBll.getWebAccountByMobile(UserInfo.Mobile);
                if (webAccount != null)
                {
                    UserInfo userInfo = new UserInfo();
                    userInfo.userName = webAccount.Name;
                    Session["userName"] = userInfo.userName;
                }
            }

            bUpdateResult = userBll.UpdatePatientVisitor(iPid, UserInfo.visitId, UserInfo.Name, UserInfo.Mobile, UserInfo.CertCode, UserInfo.IsDefault);

            if (bUpdateResult)
                return GetUserInfo();

            return Json(new ReturnCode(-1, bUpdateResult.ToString()), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 加载图片
        /// </summary>
        /// <param name="File"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadPicture(HttpPostedFileBase File)
        {
            string FileName = File.FileName;

            //上传的原文件名  
            string sPhotoName = string.Empty;
            string sUserId = Session["pid"].ToString();
            string sFileFullName = string.Empty;
            string sFileExtention = FileName.Substring(FileName.LastIndexOf(".") + 1); //得到文件的后缀名  
            if (!string.IsNullOrEmpty(FileName))
            {
                sPhotoName = sUserId + "Photo.jpg"; //得到重命名的文件名
                if (!Directory.Exists(Server.MapPath(RuiciCommoms._sUploadImgPath)))
                {
                    Directory.CreateDirectory(Server.MapPath(RuiciCommoms._sUploadImgPath));
                }
                File.SaveAs(Server.MapPath(RuiciCommoms._sUploadImgPath) + sPhotoName); //保存操作  
                sFileFullName = RuiciCommoms._sUploadImgPath + sPhotoName;

                return Json(sFileFullName, JsonRequestBehavior.AllowGet);
            }

            return Json(new ReturnCode(-1, "上传失败"), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 提交新密码
        /// </summary>
        /// <param name="UserInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveNewPassword(RegisterViewModel UserInfo)
        {
            Dictionary<int, string> UpdateResultDic = new Dictionary<int, string>();

            if (UserInfo == null)
                return Json(new ReturnCode(-1, "请检查是否填写了您的个人信息。"), JsonRequestBehavior.AllowGet);

            Dictionary<int, string> sResultDic = userInfoBll.Login(Session["mobile"].ToString(), UserInfo.originalPwd);

            if (sResultDic.First().Key == 0)
            {
                WebAccount account = userInfoBll.getWebAccountByMobile(Session["mobile"].ToString());

                if (UserInfo.Password == UserInfo.confirmPwd)
                    UpdateResultDic = userInfoBll.changePassword(account.UserName, UserInfo.Password);
                else
                    return Json(new ReturnCode(-1, "您两次输入的密码不相同，请重新输入。"), JsonRequestBehavior.AllowGet);

                return Json(new ReturnCode(UpdateResultDic.First().Key, UpdateResultDic.First().Value), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new ReturnCode(-1, "您输入的原始密码不正确。"), JsonRequestBehavior.AllowGet);
            }

        }
        /// <summary>
        /// 下载报告详情
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DownloadReportDetail(FileInfoModel fileInfo)
        {
            string sUserId = Session["pid"].ToString();
            string pdfName = sUserId + "_Report.pdf"; //得到重命名的文件名
            if (!Directory.Exists(Server.MapPath(RuiciCommoms._sUploadImgPath)))
            {
                Directory.CreateDirectory(Server.MapPath(RuiciCommoms._sUploadImgPath));
            }

            common.Use_ephtmltopdf(fileInfo.htmlContent, Server.MapPath(RuiciCommoms._sUploadImgPath) + pdfName);

            string fileUrl = RuiciCommoms._sUploadImgPath + pdfName;

            return Json(fileUrl, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 下载案例
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DownloadCase(FileInfoModel fileInfo)
        {
            string sUserId = Session["pid"].ToString();
            string pdfName = sUserId + "_Case.pdf"; //得到重命名的文件名
            if (!Directory.Exists(Server.MapPath(RuiciCommoms._sUploadImgPath)))
            {
                Directory.CreateDirectory(Server.MapPath(RuiciCommoms._sUploadImgPath));
            }

            common.Use_ephtmltopdf(fileInfo.htmlContent, Server.MapPath(RuiciCommoms._sUploadImgPath) + pdfName);

            string fileUrl = RuiciCommoms._sUploadImgPath + pdfName;

            return Json(fileUrl, JsonRequestBehavior.AllowGet);
        }


    }
}